package com.code2roc.jarmanage.depoly;

import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.util.CMDUtil;
import com.code2roc.jarmanage.util.FileUtil;
import com.code2roc.jarmanage.util.LogUtil;
import com.code2roc.jarmanage.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;

public class WindowsDepolyService implements DepolyService {
    @Override
    public void install(ProjectDO entity) {
        String exePath = entity.getJarPackagePath() + File.separator + entity.getServiceName() + ".exe";
        String xmlPath = entity.getJarPackagePath() + File.separator + entity.getServiceName() + ".xml";
        if (!new File(exePath).exists()) {
            FileUtil.copyFile("resources" + File.separator + "windows" + File.separator + "deploy.exe", exePath);
        }
        if (!new File(xmlPath).exists()) {
            FileUtil.copyFile("resources" + File.separator + "windows" + File.separator + "deploy.xml", xmlPath);
        }
        saveConfig(entity);
        String command = entity.getServiceName() + ".exe install";
        CMDUtil.executeWindowCommand(command, entity.getJarPackagePath());
    }

    @Override
    public void unInstall(ProjectDO entity) {
        String command = entity.getServiceName() + ".exe uninstall";
        CMDUtil.executeWindowCommand(command, entity.getJarPackagePath());
    }

    @Override
    public void start(ProjectDO entity) {
        String command = entity.getServiceName() + ".exe start";
        CMDUtil.executeWindowCommand(command, entity.getJarPackagePath());
    }

    @Override
    public void stop(ProjectDO entity) {
        String command = entity.getServiceName() + ".exe stop";
        CMDUtil.executeWindowCommand(command, entity.getJarPackagePath());
    }

    @Override
    public String getStatus(String serviceName) {
        String status = DepolyStatus.UnInstall;
        try {
            String command = "sc query " + serviceName;
            String commandResultFilePath = CMDUtil.executeWindowCommandStoreFile(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(commandResultFilePath)));
            String line = reader.readLine();
            while (line != null) {
                if (line.trim().startsWith("STATE")) {
                    if (line.trim().substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim().equals("1"))
                        status = DepolyStatus.Stopped;
                    else if (line.trim().substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim().equals("2"))
                        status = DepolyStatus.Startting;
                    else if (line.trim().substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim().equals("3"))
                        status = DepolyStatus.Stopping;
                    else if (line.trim().substring(line.trim().indexOf(":") + 1, line.trim().indexOf(":") + 4).trim().equals("4"))
                        status = DepolyStatus.Running;
                }
                line = reader.readLine();
            }
        } catch (IOException e) {
            LogUtil.error(e);
        }
        return status;
    }

    private void saveConfig(ProjectDO entity) {
        try {
            String xmlPath = entity.getJarPackagePath() + File.separator + entity.getServiceName() + ".xml";
            SAXReader reader = new SAXReader();
            Document document = reader.read(new FileInputStream(xmlPath));
            Element root = document.getRootElement();
            Element id = root.element("id");
            id.setText(entity.getServiceName());

            Element name = root.element("name");
            name.setText(entity.getServiceName());

            Element description = root.element("description");
            description.setText(entity.getProjectName());

            Element arguments = root.element("arguments");
            String jarPackgePath = new File(entity.getJarPackagePath()).getAbsolutePath();
            String argumentsCommand = "";
            if (!StringUtil.isEmpty(entity.getDepolyBeforeParam())) {
                argumentsCommand += " " + entity.getDepolyBeforeParam() + " ";
            }
            argumentsCommand += " -jar " + jarPackgePath + File.separator + entity.getServiceName() + ".jar";
            if (!StringUtil.isEmpty(entity.getDepolyAfterParam())) {
                argumentsCommand += " " + entity.getDepolyAfterParam() + " ";
            }
            if (!StringUtil.isEmpty(entity.getDepolyPort())) {
                argumentsCommand += "  --server.port=" + entity.getDepolyPort();
            }
            arguments.setText(argumentsCommand);

            Element jarFilePath = root.element("jarFilePath");
            jarFilePath.setText(jarPackgePath + File.separator + entity.getServiceName() + ".jar");

            Element port = root.element("port");
            port.setText(entity.getDepolyPort());

            Element logpath = root.element("logpath");
            logpath.setText(jarPackgePath + File.separator + "deploylog");

            OutputFormat xmlFormat = OutputFormat.createPrettyPrint();
            xmlFormat.setEncoding("utf-8");
            XMLWriter writer = new XMLWriter(new FileOutputStream(xmlPath), xmlFormat);
            writer.write(document);
            writer.close();

        } catch (Exception e) {
            LogUtil.error(e);
        }
    }
}
